<template>
	<view class="goods-container">
		<view class="goods-item" @click="goPage(item)" v-for="item in goodsList" :key="item._id">
			<view class="goods-image">
				<image :src="item.mainImage" mode="aspectFill"></image>
				<view class="goods-badge flex" v-if="item.isSpecialOffer">
					<text class="badge-text">特价</text>
				</view>
			</view>
			<view class="goods-info">
				<view class="goods-name">
					{{item.name}}
				</view>
				<view class="goods-shop">
					<text class="shop-icon">🏪</text>
					<text class="shop-name">{{item.shop && item.shop.name ? item.shop.name : '店铺'}}</text>
				</view>
				<view class="goods-price">
					<view class="price-info">
						<text class="current-price">￥{{getCurrentPrice(item)}}</text>
						<text class="original-price"
							v-if="getOriginalPrice(item) && getOriginalPrice(item) > getCurrentPrice(item)">
							￥{{getOriginalPrice(item)}}
						</text>
					</view>
					<view class="add-cart-btn" @click.stop="addToCart(item)">
						<text class="add-icon">+</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		AddCart
	} from "@/api/cart.js";
	import storage from "@/utils/storage.js";
	import {
		errorHandler
	} from '@/utils/errorHandler.js';

	export default {
		props: {
			goodsList: {
				type: Array,
				default: []
			}
		},
		data() {
			return {
				isAddingToCart: false
			}
		},

		methods: {
			goPage(item) {
				this.$router.smartNavigate({
					url: '/pages/homePages/sam/samGoodsInfo?id=' + item._id
				});
			},
			// 添加到购物车
			async addToCart(item) {
				// 检查登录状态
				if (!storage.getAccessToken()) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}

				// 验证库存
				if (!item.stock || item.stock <= 0) {
					uni.showToast({
						title: '商品库存不足',
						icon: 'none'
					});
					return;
				}

				// 防止重复点击
				if (this.isAddingToCart) {
					return;
				}

				this.isAddingToCart = true;

				try {
					// 调用加入购物车API
					const res = await AddCart({
						productId: item._id,
						quantity: 1
					});

					if (res.data.code === 200) {
						uni.showToast({
							title: '已添加到购物车',
							icon: 'success'
						});

						// 触发父组件更新购物车数量
						this.$emit('cartUpdated');
					} else {
						uni.showToast({
							title: res.data.message || '添加失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('加入购物车失败:', error);
					// 使用统一的错误处理
					errorHandler.showApiError(error, '加入购物车失败');
				} finally {
					this.isAddingToCart = false;
				}
			},
			// 获取当前价格（优先使用 displayPrice 和 currentPrice）
			getCurrentPrice(item) {
				// 如果有price字段，显示price
				if (item.price && item.price > 0) {
					return item.price.toFixed(2);
				}
				// 如果都没有，显示0
				return '0.00';
			},
			// 获取原价（用于显示划线价格）
			getOriginalPrice(item) {
				// 如果是特价商品，原价应该是originalPrice
				if (item.isSpecialOffer) {
					return item.originalPrice || 0;
				}
				// 如果不是特价商品，返回0（不显示划线价格）
				return 0;
			},
			//计算单个商品价格
			finalPrice(goodsItem) {
				const basePrice = goodsItem.price

				if (!goodsItem.isSpecialOffer) {
					return basePrice.toFixed(2); // 普通商品直接显示
				}

				// 特价商品计算逻辑
				const discount = goodsItem.specialOfferInfo.discountRate * 0.1;
				return (basePrice * discount).toFixed(2);
			},
		}
	}
</script>

<style scoped lang="scss">
	.goods-container {
		width: 100%;
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20rpx;
	}

	.goods-item {
		background: white;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
		transition: all 0.3s ease;
		position: relative;

		&:active {
			transform: translateY(-4rpx);
			box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.12);
		}

		.goods-image {
			position: relative;
			width: 100%;
			height: 240rpx;
			overflow: hidden;

			image {
				width: 100%;
				height: 100%;
				transition: transform 0.3s ease;
			}

			&:hover image {
				transform: scale(1.05);
			}

			.goods-badge {
				position: absolute;
				top: 16rpx;
				left: 16rpx;
				background: linear-gradient(135deg, #FF4D4F 0%, #FF7875 100%);
				border-radius: 20rpx;
				padding: 8rpx 16rpx;

				.badge-text {
					color: white;
					font-size: 20rpx;
					font-weight: 600;
				}
			}
		}

		.goods-info {
			padding: 20rpx;

			.goods-name {
				font-size: 28rpx;
				font-weight: 600;
				color: #333;
				line-height: 1.4;
				margin-bottom: 12rpx;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				overflow: hidden;
				min-height: 80rpx;
			}

			.goods-shop {
				display: flex;
				align-items: center;
				margin-bottom: 16rpx;

				.shop-icon {
					font-size: 24rpx;
					margin-right: 8rpx;
				}

				.shop-name {
					font-size: 24rpx;
					color: #666;
					flex: 1;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
			}

			.goods-price {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.price-info {
					display: flex;
					align-items: center;
					gap: 8rpx;

					.current-price {
						font-size: 32rpx;
						font-weight: 700;
						color: #FF2E44;
					}

					.original-price {
						font-size: 24rpx;
						color: #999;
						text-decoration: line-through;
					}
				}

				.add-cart-btn {
					width: 56rpx;
					height: 56rpx;
					background: linear-gradient(135deg, #FF6B35 0%, #FE6100 50%, #FF8A00 100%);
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					box-shadow: 0 4rpx 16rpx rgba(254, 97, 0, 0.3);
					transition: all 0.3s ease;

					&:active {
						transform: scale(0.9);
						box-shadow: 0 2rpx 8rpx rgba(254, 97, 0, 0.4);
					}

					.add-icon {
						color: white;
						font-size: 32rpx;
						font-weight: 600;
					}
				}
			}
		}
	}

	// 兼容旧样式
	.goods {
		width: 100%;
		display: grid;
		grid-template-columns: repeat(2, minmax(140px, 1fr));
		gap: 10px;

		.goods_item {

			padding: 24rpx;
			background-color: #fff;
			border-radius: 8rpx;

			.goods_info_title {
				padding: 12rpx 0;
				font-weight: 700;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				min-width: 0;
				/* 关键！允许内容收缩 */
			}

			.goods_img {
				width: 100%;
				height: 100px;
				border-radius: 8rpx;
				overflow: hidden;
			}

			.goods_info_add {
				color: #fff;
				width: 36rpx;
				height: 36rpx;
				line-height: 36rpx;
				text-align: center;
				font-weight: 700;
				border-radius: 50%;
				background-color: #fb6c34;
			}
		}
	}

	.originalPrice {
		font-size: 24rpx;
		color: rgba(0, 0, 0, .5);
		text-decoration: line-through;
	}
</style>